package cn.iocoder.yudao.module.member.service.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberDockerTjPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserUpdateReqVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.*;
import cn.iocoder.yudao.module.member.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.member.convert.user.MemberUserConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import cn.iocoder.yudao.module.member.mq.producer.user.MemberUserProducer;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 会员 User Service 实现类
 *
 * @author 档案
 */
@Service
@Valid
@Slf4j
public class MemberUserServiceImpl implements MemberUserService {

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private MemberUserProducer memberUserProducer;

    @Override
    public MemberUserDO getUserByMobile(String mobile,Integer userType) {
        return memberUserMapper.selectByMobile(mobile,userType);
    }

    @Override
    public List<MemberUserDO> getUserListByNickname(String nickname,Integer userType) {
        return memberUserMapper.selectListByNicknameLike(nickname,userType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MemberUserDO createUserIfAbsent(String mobile, String registerIp, Integer terminal,Integer userType) {
        // 用户已经存在
        MemberUserDO user = memberUserMapper.selectByMobile(mobile,userType);
        if (user != null) {
            return user;
        }
        // 用户不存在，则进行创建
        return createUser(mobile, registerIp, terminal,userType);
    }

    private MemberUserDO createUser(String mobile, String registerIp, Integer terminal,Integer userType) {
        // 生成密码
        String password = IdUtil.fastSimpleUUID();
        // 插入用户
        MemberUserDO user = new MemberUserDO();
        user.setMobile(mobile);
        user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
        user.setPassword(encodePassword(password)); // 加密密码
        user.setRegisterIp(registerIp);
        user.setRegisterTerminal(terminal);
        user.setUserType(userType);
        memberUserMapper.insert(user);

        // 发送 MQ 消息：用户创建
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {

            @Override
            public void afterCommit() {
                memberUserProducer.sendUserCreateMessage(user.getId());
            }

        });
        return user;
    }

    @Override
    public void updateUserLogin(Long id, String loginIp) {
        memberUserMapper.updateById(new MemberUserDO().setId(id)
                .setLoginIp(loginIp).setLoginDate(LocalDateTime.now()));
    }

    @Override
    public MemberUserDO getUser(Long id) {
        return memberUserMapper.selectById(id);
    }

    @Override
    public List<MemberUserDO> getUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return memberUserMapper.selectBatchIds(ids);
    }

    @Override
    public void updateUser(Long userId, AppMemberUserUpdateReqVO reqVO) {
        MemberUserDO memberUserDO = new MemberUserDO().setId(userId);
        BeanUtils.copyProperties(reqVO,memberUserDO);
        memberUserMapper.updateById(memberUserDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserMobile(Long userId, AppMemberUserUpdateMobileReqVO reqVO) {
        // 检测用户是否存在
        MemberUserDO user = validateUserExists(userId);
        // 校验新手机是否已经被绑定
        validateMobileUnique(null, reqVO.getMobile(),reqVO.getUserType());

        // 校验旧手机和旧验证码
        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO().setMobile(user.getMobile()).setCode(reqVO.getOldCode())
                .setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene()).setUsedIp(getClientIP()));
        // 使用新验证码
        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO().setMobile(reqVO.getMobile()).setCode(reqVO.getCode())
                .setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene()).setUsedIp(getClientIP()));

        // 更新用户手机
        memberUserMapper.updateById(MemberUserDO.builder().id(userId).mobile(reqVO.getMobile()).build());
    }

    @Override
    public void updateUserPassword(Long userId, AppMemberUserUpdatePasswordReqVO reqVO) {
        // 检测用户是否存在
        MemberUserDO user = validateUserExists(userId);
        // 校验验证码
        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO().setMobile(user.getMobile()).setCode(reqVO.getCode())
                .setScene(SmsSceneEnum.MEMBER_UPDATE_PASSWORD.getScene()).setUsedIp(getClientIP()));

        // 更新用户密码
        memberUserMapper.updateById(MemberUserDO.builder().id(userId)
                .password(passwordEncoder.encode(reqVO.getPassword())).build());
    }

    @Override
    public void resetUserPassword(AppMemberUserResetPasswordReqVO reqVO) {
        // 检验用户是否存在
        MemberUserDO user = validateUserExists(reqVO.getMobile(),reqVO.getUserType());

        // 使用验证码
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_RESET_PASSWORD,
                getClientIP()));

        // 更新密码
        memberUserMapper.updateById(MemberUserDO.builder().id(user.getId())
                .password(passwordEncoder.encode(reqVO.getPassword())).build());
    }

    private MemberUserDO validateUserExists(String mobile,Integer userType) {
        MemberUserDO user = memberUserMapper.selectByMobile(mobile,userType);
        if (user == null) {
            throw exception(USER_MOBILE_NOT_EXISTS);
        }
        return user;
    }

    @Override
    public boolean isPasswordMatch(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 对密码进行加密
     *
     * @param password 密码
     * @return 加密后的密码
     */
    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(MemberUserUpdateReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 校验手机唯一
        validateMobileUnique(updateReqVO.getId(), updateReqVO.getMobile(),updateReqVO.getUserType());

        // 更新
        MemberUserDO updateObj = MemberUserConvert.INSTANCE.convert(updateReqVO);
        memberUserMapper.updateById(updateObj);
    }

    @VisibleForTesting
    MemberUserDO validateUserExists(Long id) {
        if (id == null) {
            return null;
        }
        MemberUserDO user = memberUserMapper.selectById(id);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        return user;
    }

    @VisibleForTesting
    void validateMobileUnique(Long id, String mobile,Integer userType) {
        if (StrUtil.isBlank(mobile)) {
            return;
        }
        MemberUserDO user = memberUserMapper.selectByMobile(mobile,userType);
        if (user == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的用户
        if (id == null) {
            throw exception(USER_MOBILE_USED, mobile);
        }
        if (!user.getId().equals(id)) {
            throw exception(USER_MOBILE_USED, mobile);
        }
    }

    @Override
    public PageResult<MemberUserDO> getUserPage(MemberUserPageReqVO pageReqVO) {
        return memberUserMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateUserLevel(Long id, Long levelId, Integer experience) {
        // 0 代表无等级：防止UpdateById时，会被过滤掉的问题
        levelId = ObjectUtil.defaultIfNull(levelId, 0L);
        memberUserMapper.updateById(new MemberUserDO()
                .setId(id)
                .setLevelId(levelId).setExperience(experience)
        );
    }

    @Override
    public Long getUserCountByGroupId(Long groupId) {
        return memberUserMapper.selectCountByGroupId(groupId);
    }

    @Override
    public Long getUserCountByLevelId(Long levelId) {
        return memberUserMapper.selectCountByLevelId(levelId);
    }

    @Override
    public Long getUserCountByTagId(Long tagId) {
        return memberUserMapper.selectCountByTagId(tagId);
    }

    @Override
    public boolean updateUserPoint(Long id, Integer point) {
        if (point > 0) {
            memberUserMapper.updatePointIncr(id, point);
        } else if (point < 0) {
            return memberUserMapper.updatePointDecr(id, point) > 0;
        }
        return true;
    }

    @Override
    public boolean updateAuthentication(AppMemberUserUpdateAuthenticationReqVO reqVO) {
        MemberUserDO memberUserDO = new MemberUserDO();
        BeanUtils.copyProperties(memberUserDO, reqVO);
        memberUserDO.setId(getLoginUserId());
        int count = memberUserMapper.updateById(memberUserDO);
        if (count>0) {
            return true;
        }
        return false;
    }

    @Override
    public PageResult<MemberUserDO> selectTjDocker(MemberDockerTjPageReqVO pageVO) {
        return memberUserMapper.selectDockerList(pageVO);
    }

    @Override
    public boolean updatePop(Long loginUserId) {
        MemberUserDO memberUserDO = new MemberUserDO();
        memberUserDO.setId(loginUserId);
        memberUserDO.setPop_set(1);
        int count = memberUserMapper.updateById(memberUserDO);
        if (count>0) {
            return true;
        }
        return false;
    }

    @Override
    public MemberUserDO getDockerLoginInfo(Long loginUserId) {
        return memberUserMapper.selectOne(new LambdaQueryWrapper<MemberUserDO>()
                .eq(MemberUserDO::getUserType,3)
                .eq(MemberUserDO::getId, loginUserId));
    }

    @Override
    public int updateNum(String field) {
        MemberUserDO dockerLoginInfo = getDockerLoginInfo(getLoginUserId());

        if (field=="patientNum") {
            Integer num= 0;
            if (dockerLoginInfo.getPatientNum()!=null && dockerLoginInfo.getPatientNum()>0) {
                num=dockerLoginInfo.getPatientNum();
            }
            dockerLoginInfo.setPatientNum(num+1);
            return memberUserMapper.updateById(dockerLoginInfo);
        }else if (field=="extractionNum") {
            Integer num= 0;
            if (dockerLoginInfo.getExtractionNum()!=null && dockerLoginInfo.getExtractionNum()>0) {
                num=dockerLoginInfo.getExtractionNum();
            }
            dockerLoginInfo.setExtractionNum(num+1);
            return memberUserMapper.updateById(dockerLoginInfo);
        }else if (field=="consultNum"){
            Integer num= 0;
            if (dockerLoginInfo.getConsultNum()!=null && dockerLoginInfo.getConsultNum()>0) {
                num=dockerLoginInfo.getConsultNum();
            }
            dockerLoginInfo.setConsultNum(num+1);
            return memberUserMapper.updateById(dockerLoginInfo);
        }
        return 0;
    }

    @Override
    public void updateDoctor(AppMemberDoctorUpdateReqVO reqVO) {
        MemberUserDO memberUserDO = MemberUserConvert.INSTANCE.convertDoctorUpdate(reqVO);
        if(StringUtils.isNotBlank(memberUserDO.getIdentityCard())){
            verifyIdentityCard(memberUserDO.getIdentityCard());
        }
        memberUserMapper.updateById(memberUserDO);
    }

    @Override
    public MemberUserDO selectById(Long id) {

        return memberUserMapper.selectById(id);
    }

    @Override
    public void deleteUser( Long userType) {
        if (userType!=null && userType==3 || userType==4) {
            MemberUserDO memberUserDO = memberUserMapper.selectOne(new LambdaQueryWrapperX<MemberUserDO>()
                    .eq(MemberUserDO::getUserType,userType)
                    .eq(MemberUserDO::getCreator, getLoginUserId()));
            memberUserMapper.deleteById(memberUserDO);
        }else {
            MemberUserDO memberUserDO = memberUserMapper.selectOne(new LambdaQueryWrapperX<MemberUserDO>()
                    .eq(MemberUserDO::getCreator, getLoginUserId()));
            memberUserMapper.deleteById(memberUserDO);
        }
    }

    @Override
    public void deleteUserLogin() {
        LoginUser loginUser = getLoginUser();

        memberUserMapper.deleteById(loginUser.getId());
    }

    public IdcardUtil.Idcard verifyIdentityCard(String  card) {
        String idNum=card.toUpperCase();
        boolean validCard = IdcardUtil.isValidCard(idNum);
        if(!validCard) {
            throw exception(TREATMENT_USER_NOT_EXISTS_IDENTITYCARD);
        }
        return IdcardUtil.getIdcardInfo(idNum);
    }

}
